from django.contrib.auth.decorators import login_required
from django.db.models import Q
from django.shortcuts import render, redirect, reverse
from .models import *
from django.views.decorators.http import require_http_methods, require_POST, require_GET
# Create your views here.

def index(request):
    blogs = BlogModel.objects.all().order_by('-pub_time')
    return render(request, 'index.html', {'blogs':blogs})

# 博客详情
def blog_detail(request, blog_id):
    try:
        blog = BlogModel.objects.get(id=blog_id)
    except Exception as e:
        print(e)
        blog=None
    return render(request, 'blog_detail.html', {'blog':blog})


# 发布评论
@require_POST               # 限制post请求
@login_required()           # 限制登录
def pub_comment(request):
    blog_id = request.POST.get('blog_id')
    content = request.POST.get('content')
    BlogCommentModel.objects.create(content=content, blog_id=blog_id, author=request.user)
    # 重新加载博客详情页
    return redirect(reverse("app:detail", kwargs={'blog_id':blog_id}))


# 搜索功能
@require_GET
def search(request):
    key = request.GET.get('key')
    # 从博客的标题和内容中搜索
    blogs = BlogModel.objects.filter(Q(title__contains=key) | Q(content__contains=key)).all().order_by('-pub_time')
    return render(request, 'index.html', {'blogs':blogs})